package com.nku.mason.scm.controller;

import java.io.IOException;
import java.util.Arrays;

import javax.annotation.Resource;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.nku.mason.scm.service.BuyOrderService;
import com.nku.mason.scm.vo.BuyOrder;
import com.nku.mason.scm.vo.BuyOrderDetail;

@Controller
@RequestMapping("/buyOrder")
public class BuyOrderAction {

	@Resource
	private BuyOrderService buyOrderService;

	@RequestMapping("/insertBuyOrderOnForm")
	@ResponseBody
	public Object insertBuyOrderOnForm(BuyOrder buyOrder, String rows)
			throws JsonParseException, JsonMappingException, IOException {
		// request.getParameter("rows");
		System.out.println("buyorderaction.buyOrder：" + buyOrder);
		System.out.println("buyorderaction.把json作为字符串的采购单明细：" + rows);
		int i = 0;
		ObjectMapper objectMapper = new ObjectMapper();
		// BuyOrderDetail o = objectMapper.readValue(rows[0],
		// BuyOrderDetail.class);
		// System.out.println("oooooooooo:"+o);
		BuyOrderDetail[] buyOrderDetails = null;
		try {
			// 把json格式的字符串转为java对象数组
			buyOrderDetails = objectMapper.readValue(rows, BuyOrderDetail[].class);
			// Arrays.asList把普通JAVA数组转为list对象
			buyOrder.setBuyOrderDetails(Arrays.asList(buyOrderDetails));
			i = buyOrderService.insertBuyOrder(buyOrder);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		return i;

	}

	@RequestMapping("/insertBuyOrder")
	@ResponseBody
	public Object insertBuyOrder(String buyOrder) {
		System.out.println("buyorderaction.rows：" + buyOrder);

		int i = 0;
		// ObjectMapper是工具类，用来把json格式内容与JAVA对象之间进行转换
		ObjectMapper objectMapper = new ObjectMapper();
		try {
			// 把包含json格式的字符串转为BuyOrder类型对象
			BuyOrder bo = objectMapper.readValue(buyOrder, BuyOrder.class);
			System.out.println("buyOrder:" + bo);
			i = buyOrderService.insertBuyOrder(bo);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		return i;
	}

}
